package nio.socket.block;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;

/**
 * 客户端
 */
public class Client {
    /**
     * 客户端1秒钟发送一次请求获取服务器端时间，期间一直保持TCP连接不关闭
     */
    public static void post(String host, int port,long keepalive) {
        BufferedReader reader = null;
        PrintWriter writer = null;
        Socket client = null;
        try {
            client = new Socket(host,port);
            writer = new PrintWriter(client.getOutputStream());
            reader = new BufferedReader(new InputStreamReader(client.getInputStream()));
            long endTime = 0;
            do {
                writer.println("GET CURRENT TIME");
                writer.flush();
                String response = reader.readLine();
                System.out.println(Thread.currentThread().getName()+" Get Current Time:" + response);
                if (endTime == 0) { // 成功连接后才开始计算存活时间
                    endTime=System.currentTimeMillis()+keepalive;
                }
                Thread.sleep(1000); //在存活期间，每1秒钟获取一次服务器时间
            } while (System.currentTimeMillis() < endTime);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                writer.close();
                reader.close();
                client.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }

}
